import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { 
  Card, 
  Row, 
  Col, 
  Typography, 
  Button, 
  List, 
  Divider, 
  Radio, 
  Space, 
  message, 
  Modal 
} from 'antd';
import { 
  ClockCircleOutlined, 
  CreditCardOutlined, 
  WalletOutlined, 
  AlipayCircleOutlined 
} from '@ant-design/icons';
import '../styles/OrderConfirmation.css';
import axios from 'axios';
import { jwtDecode } from 'jwt-decode';

const { Title, Text } = Typography;

// 2. 添加辅助函数获取当前用户
const getCurrentUser = () => {
  try {
    const token = localStorage.getItem('token');
    if (token) {
      return jwtDecode(token);
    }
  } catch (error) {
    console.error("Failed to decode token", error);
    return null;
  }
  return null;
};

const OrderConfirmation = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [order, setOrder] = useState({});
  const [countdown, setCountdown] = useState(900); // 15 minutes in seconds
  const [paymentMethod, setPaymentMethod] = useState('creditCard');
  // Removed loading and orderSuccess states for simplification and debugging

  // Get order data from location state or use mock data as fallback
  useEffect(() => {
    if (location.state && location.state.order) {
      // Use the order data passed from seat selection page
      setOrder(location.state.order);
    } else {
      // Fallback to mock data if no state is passed
      const mockOrder = {
        id: 'ORD' + Math.floor(Math.random() * 1000000),
        movie: '流浪地球2',
        cinema: '星光影院',
        hall: '1号厅',
        date: '2023-05-15',
        time: '10:00:00',
        seats: ['4排15座'],
        ticketPrice: 35,
        serviceCharge: 5,
        totalAmount: 40,
      };
      setOrder(mockOrder);
    }
  }, [location.state]);

  // Countdown timer
  useEffect(() => {
    if (countdown > 0) {
      const timer = setTimeout(() => setCountdown(countdown - 1), 1000);
      return () => clearTimeout(timer);
    } else {
      // Time's up - redirect to home or show expired modal
      Modal.error({
        title: '订单已超时',
        content: '您的订单已超过15分钟未支付，已自动取消。座位已释放。',
        onOk: () => navigate('/'),
      });
    }
  }, [countdown, navigate]);

  // Format countdown time as MM:SS
  const formatTime = (seconds) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  const handlePaymentChange = (e) => {
    setPaymentMethod(e.target.value);
  };

  const handlePayment = async () => {
    console.log('Payment button clicked! Attempting to send order to backend.');
    try {
      const formattedShowtime = `${order.date.trim()}T${order.time.trim()}`;
      const seatsString = order.seats?.join(', ') || '';
      const orderNumber = 'ORD' + Math.floor(Math.random() * 1000000);

      const currentUser = getCurrentUser(); // 3. 获取当前用户
      if (!currentUser || !currentUser.userId) {
        message.error("无法获取用户信息，请重新登录。");
        return;
      }
      
      const token = localStorage.getItem('token'); // 4. 获取token

      const response = await axios.post('http://localhost:8080/api/orders', {
        orderNumber: orderNumber,
        movieTitle: order.movie,
        cinemaName: order.cinema,
        hallName: order.hall,
        showtime: formattedShowtime,
        seats: seatsString,
        quantity: order.seats?.length || 0,
        ticketPrice: order.ticketPrice,
        serviceFee: order.serviceCharge,
        totalPrice: order.totalAmount,
        paymentMethod: paymentMethod,
        userId: currentUser.userId, // 5. 使用动态userId
      }, {
        headers: { // 6. 添加 Authorization header
          'Authorization': `Bearer ${token}`
        }
      });
      console.log('Order created successfully:', response.data);
      message.success('支付成功！');
      navigate('/payment/success', { state: { orderNumber: response.data.orderNumber } });
    } catch (error) {
      console.error('Error creating order:', error);
      message.error('支付失败，请稍后再试！');
      Modal.error({
        title: '支付失败',
        content: `支付过程中发生错误，请检查网络或稍后再试。`,
        onOk: () => {},
      });
    }
  };

  return (
    <div className="order-confirmation">
      <Title level={2}>确认订单</Title>
      
      <div className="countdown-timer">
        <ClockCircleOutlined /> 请在 <Text type="danger">{formatTime(countdown)}</Text> 内完成支付
      </div>
      
      <Row gutter={[24, 24]}>
        <Col xs={24} md={16}>
          <Card title="订单信息" className="order-card">
            <List>
              <List.Item>
                <Text strong>电影：</Text>
                <Text>{order.movie}</Text>
              </List.Item>
              <List.Item>
                <Text strong>影院：</Text>
                <Text>{order.cinema}</Text>
              </List.Item>
              <List.Item>
                <Text strong>影厅：</Text>
                <Text>{order.hall}</Text>
              </List.Item>
              <List.Item>
                <Text strong>场次：</Text>
                <Text>{order.date} {order.time}</Text>
              </List.Item>
              <List.Item>
                <Text strong>座位：</Text>
                <Text>{order.seats?.join(', ') || '未选择'}</Text>
              </List.Item>
            </List>
          </Card>
          
          <Card title="支付方式" className="payment-card">
            <Radio.Group onChange={handlePaymentChange} value={paymentMethod}>
              <Space direction="vertical" className="payment-methods">
                <Radio value="creditCard">
                  <CreditCardOutlined /> 信用卡支付
                </Radio>
                <Radio value="wallet">
                  <WalletOutlined /> 电子钱包
                </Radio>
                <Radio value="alipay">
                  <AlipayCircleOutlined /> 支付宝
                </Radio>
              </Space>
            </Radio.Group>
          </Card>
        </Col>
        
        <Col xs={24} md={8}>
          <Card title="订单摘要" className="order-summary">
            <List>
              <List.Item>
                <Text>票价 ({order.seats?.length || 0} x ¥{order.ticketPrice || 0})</Text>
                <Text>¥{((order.ticketPrice || 0) * (order.seats?.length || 0)).toFixed(2)}</Text>
              </List.Item>
              <List.Item>
                <Text>服务费</Text>
                <Text>¥{order.serviceCharge || 0}</Text>
              </List.Item>
              <Divider />
              <List.Item>
                <Text strong>总计</Text>
                <Text strong className="total-amount">¥{order.totalAmount || 0}</Text>
              </List.Item>
            </List>
            
            <Button 
              type="primary" 
              size="large" 
              block 
              className="pay-button"
              onClick={handlePayment}
            >
              立即支付 ¥{order.totalAmount || 0}
            </Button>
            
            <div className="cancel-order">
              <Button type="link" onClick={() => {
                // Get screening ID from state if available, or use a default
                const screeningId = location.state?.screeningId || 1;
                navigate(`/screening/${screeningId}/select-seats`);
              }}>
                返回座位选择
              </Button>
            </div>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default OrderConfirmation; 